package com.nobuyme.box.toy;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.nobuyme.box.R;
import com.nobuyme.box.app.UrlCenter;
import com.nobuyme.box.bean.GetIndex;
import com.nobuyme.box.bean.GoodsDetailEntity;
import com.nobuyme.box.util.FragmentUtils;
import com.nobuyme.box.util.StrokeTextView;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.framework.httprequest.HttpRequest;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.frameworkbase.utils.EasyToast;

import java.io.UnsupportedEncodingException;

import butterknife.Bind;
import butterknife.OnClick;

public class ToyIntroduceActivity extends BaseActivity {

    @Bind(R.id.iv_introduce_scode)
    ImageView mIvIntroduceScode;
    @Bind(R.id.iv_detail_one)
    ImageView mIvDetailOne;
    @Bind(R.id.iv_detail_two)
    ImageView mIvDetailTwo;
    @Bind(R.id.tv_detail_title)
    TextView mTvDetailTitle;
    @Bind(R.id.tv_lattet_position)
    TextView mTvLattetPosition;
    @Bind(R.id.tv_introude_content)
    TextView mTvIntroudeContent;
    @Bind(R.id.tv_introude_rule1)
    TextView mTvIntroudeRule1;
    @Bind(R.id.tv_introude_rule2)
    TextView mTvIntroudeRule2;
    @Bind(R.id.tv_detail_price)
    TextView mTvDetailPrice;
    private MyCountDownTimer mc;
    @Bind(R.id.stv_bottom_time)
    StrokeTextView mStvBottomTime;
    public static final String KEY_FLAG = "key_flag";
    int position;
    ToyListFragment.TestBean data;
    int id;
    int goods_id;
    public static final String KEY_CONTENT="content";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hideToolbar();
        data = (ToyListFragment.TestBean) getIntent().getSerializableExtra("data");
        goods_id = data.getGoods_id();
//       EasyToast.showToast(getApplicationContext(),"第一次的"+goods_id+"");
        position = getIntent().getIntExtra("position", -1);
        mc = new MyCountDownTimer(60000, 1000);
        mc.start();
        initRentTroduce();
    }

    private void initRentTroduce() {
        String urlGoodsDetail = String.format(UrlCenter.GETINDEX, data.getLattice_id());
        HttpRequest request = new HttpRequest(this);
        request.get(urlGoodsDetail, null, new DataRequestListener<GetIndex>(GetIndex.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }
            @Override
            public void onSuccess(GetIndex o) {

                super.onSuccess(o);
                setView(o.getPosition());
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    public void setView(final int position) {
        String urlGoodsDetail = String.format(UrlCenter.GOODS_DETAIL, data.getLattice_id());
        HttpRequest request = new HttpRequest(this);
        request.get(urlGoodsDetail, null, new DataRequestListener<GoodsDetailEntity>(GoodsDetailEntity.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(GoodsDetailEntity o) {
                super.onSuccess(o);
                id = o.getId();
                Glide.with(ToyIntroduceActivity.this).load(o.getToy_pic_list().get(0)).into(mIvDetailOne);
                Glide.with(ToyIntroduceActivity.this).load(o.getToy_pic_list().get(1)).into(mIvDetailTwo);
                mTvDetailTitle.setText(o.getName());
                mTvLattetPosition.setText(position + "号箱");
                mTvIntroudeContent.setText(o.getSummary());
                mTvIntroudeRule1.setText("前"+o.getLeast_rent_days()+"天"+o.getFirst_rent_price()+"元" );
                mTvIntroudeRule2.setText("第"+(o.getLeast_rent_days()+1)+"天起"+o.getLease_price() +"元/天");
                mTvDetailPrice.setText("吊牌价："+o.getTag_price()+"元");
                WebDetailFragment menuFrag =WebDetailFragment.newInstance(o.getContent());
                FragmentUtils.replaceFragment(getSupportFragmentManager(),R.id.fl_detail,menuFrag);

                int latterId = o.getLattice_id();
                initScore(latterId);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }



    String result_url;
    //设置二维码
    private void initScore(int latterId) {
        Bitmap mBitmap = null;
        String str = String.format(UrlCenter.START_RENT, latterId);
        try {
            String s = new String(Base64.encode(str.getBytes("utf-8"), Base64.NO_WRAP),"utf-8");
            result_url = String.format(UrlCenter.SCAN_ADRESS, s);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
//        String str = "http://toybox.nobuyme.com/#/rent?latticeId={}";
        if (TextUtils.isEmpty(result_url)) {
            Toast.makeText(ToyIntroduceActivity.this, "您的输入为空!", Toast.LENGTH_SHORT).show();
            return;
        }else {
            Glide.with(ToyIntroduceActivity.this).load(result_url).diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache( true ).into(mIvIntroduceScode);
        }
    }

    public static void start(Activity activity, ToyListFragment.TestBean data, String position) {
        Intent intent = new Intent(activity, ToyIntroduceActivity.class);
        intent.putExtra("data", data);
        intent.putExtra("position", position);
        activity.startActivity(intent);

    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.activity_toy_introduce, null);
        return inflate;
    }


    @OnClick({R.id.iv_introduce_back,R.id.btn_share})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_introduce_back:
                if (mc != null) {
                    mc.cancel();
                }
                finish();
                break;

            case R.id.btn_share:
                if (mc != null) {
                    mc.cancel();
                }
                ToyShareActivity.start(ToyIntroduceActivity.this,goods_id);
                break;
        }
    }


    /**
     * 继承 CountDownTimer 防范
     * <p>
     * 重写 父类的方法 onTick() 、 onFinish()
     */
    class MyCountDownTimer extends CountDownTimer {
        /**
         * @param millisInFuture    表示以毫秒为单位 倒计时的总数
         *                          <p>
         *                          例如 millisInFuture=1000 表示1秒
         * @param countDownInterval 表示 间隔 多少微秒 调用一次 onTick 方法
         *                          <p>
         *                          例如: countDownInterval =1000 ; 表示每1000毫秒调用一次onTick()
         */
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            finish();
        }

        @Override
        public void onTick(long millisUntilFinished) {
            if (mStvBottomTime != null) {
                mStvBottomTime.setText(millisUntilFinished / 1000 + "s");
            }

        }
    }

}
